<?php


namespace app\blog\controller\v1;


use app\BaseController;
use app\blog\model\ArticleModel;
use app\blog\service\ArticleService;
use app\blog\Validate\article\GetArticleValidate;
use app\common\validate\IdMustIntValidate;
use think\facade\Db;

class Article extends BaseController
{
    /**
     * 获取文章列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getArticleList() {
        $param = (new GetArticleValidate())->validateParam();
        $articleList = (new ArticleService())->getArticleList($param);
        if ($articleList) {
            return successJson($articleList, "success");
        }
        return errorJson(60004, "error");
    }

    /**
     * 通过id查找文章详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArticle() {
        $param = (new IdMustIntValidate())->validateParam();
        $changeNum = ArticleService::articleReadNum($param['id'], $this->request->ip());
        if($changeNum){
            // 数据库对应的阅读量增加1
            Db::table('blog_admin_article')
                ->where('id', '=', $param['id'])
                ->inc('article_read')
                ->update();
        }
        $result = (new ArticleModel())->getArticleById($param['id']);
        if ($result) {
            return successJson($result, "success");
        }
        return errorJson(60004, "error");
    }
}